﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;

namespace ProtocolConversion_WINCE
{
   public class BDCommunication 
    {       

        #region 字段

        private SerialPort sp;
        private static string strPortName = "COM1";
        private static string strBaudRate = "115200";
        private static string strDataBits = "8";
        private static string strStopBits = "1";
        private static bool IsSet = false;
        private static bool isStar = false;

        private Thread _readThread;
        private bool _keepReading;
        private Boolean isSerialPortOpen = false;

        private Form1 form1;        

        #endregion   

        public BDCommunication(Form1 form1)
        {
            this.form1 = form1;
            Init ();
        }
        //初始化
        private void Init()
        {
            _readThread = new Thread(ReadPort);
            _readThread.IsBackground = true;
            OpenPort();
            form1.AppendString("北斗组件初始化成功");
        }
        //打开串口
        public void OpenPort()
        {
            sp = new SerialPort();
            sp.ReadTimeout = 500;
            sp.WriteTimeout = 500;
            sp.ReadBufferSize = 1024;
            sp.PortName = strPortName;
            sp.BaudRate = int.Parse(strBaudRate);
            sp.DataBits = int.Parse(strDataBits);
            sp.StopBits = (StopBits)int.Parse(strStopBits);

            if (!isSerialPortOpen)
            {
                if (!sp.IsOpen)
                {
                    try
                    {
                        sp.Open();
                        isSerialPortOpen = true;
                    }
                    catch (Exception ex)
                    {
                        form1.AppendString("警告！北斗串口未打开，无法使用北斗通信，请确保通信接口正常"+ ex.ToString ());
                        return;
                    }
                    form1.AppendString("北斗通信串口已打开");
                }
                _keepReading = true;
                if (!isStar)
                {
                    _readThread.Start();
                    isStar = true;
                }
                else
                {
                    try
                    {
                        //weince 线程无法挂起，没有执行线程挂起的方法
                        //_readThread.Resume();
                        //_readThread.Start();

                    }
                    catch { }
                }
            }
        }
        //关闭串口
        public void ClosePort()
        {
            if (isSerialPortOpen)
            {
                _keepReading = false;
                if (isStar)
                {
                    try
                    {
                        //_readThread.Suspend();
                        _readThread.Abort();
                    }
                    catch { }
                }
                if (sp.IsOpen)
                {
                    sp.Close();
                    
                }
                isSerialPortOpen = false;
            }
        }       
        //串口接收数据函数
        private void ReadPort()
        {
            byte[] readBuffer = new byte[300];
            int bytecount = 0; 
            byte tmp = 0;
            DateTime startTime = DateTime.Now;
            while (_keepReading)  //读状态
            {
                if (sp.IsOpen)    //串口打开
                {
                    try
                    {
                        try
                        {
                            tmp = (byte)sp.ReadByte();
                        }
                        catch { }

                        if (bytecount != 0)//计数不为0说明已经检测到$
                        {
                            if ((tmp == (byte)0x24 && bytecount > 10 && Datalen(readBuffer) == bytecount) || (tmp != (byte)0x24 && bytecount > 10 && Datalen(readBuffer) == bytecount))
                            {
                                string str = byteToHexStr(readBuffer, bytecount);//将byte数组转换位hexstring
                                if (str.StartsWith("2449435858"))//$ICXX
                                {
                                    byte[] address = new byte[] { (byte)0, readBuffer[7], readBuffer[8], readBuffer[9] };
                                    byte[] tb = new byte[] { (byte)0, readBuffer[11], readBuffer[12], readBuffer[13] };
                                    byte[] freq = new byte[] { readBuffer[15], readBuffer[16] };
                                    byte[] level = new byte[] { (byte)0, readBuffer[17] };
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(address);
                                        Array.Reverse(level);
                                        Array.Reverse(freq);
                                        Array.Reverse(tb);
                                    }
                                    int vaddr = BitConverter.ToInt32(address, 0); //                                                                            
                                    int vtb = BitConverter.ToInt32(tb, 0);
                                    Int16 vfreq = BitConverter.ToInt16(freq, 0);
                                    Int16 vlevel = BitConverter.ToInt16(level, 0);
                                    form1.AppendString(DateTime.Now.ToString() + " IC信息:卡号" + vaddr + "  通播：" + vtb + "   频度：" + vfreq + "   等级:" + vlevel);
                                }
                                else if (str.StartsWith("24474C5A4B"))
                                {
                                    byte[] one = new byte[] { (byte)0, readBuffer[10] };
                                    byte[] two = new byte[] { (byte)0, readBuffer[11] };
                                    byte[] three = new byte[] { (byte)0, readBuffer[12] };
                                    byte[] four = new byte[] { (byte)0, readBuffer[13] };
                                    byte[] five = new byte[] { (byte)0, readBuffer[14] };
                                    byte[] six = new byte[] { (byte)0, readBuffer[15] };
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(one);
                                        Array.Reverse(two);
                                        Array.Reverse(three);
                                        Array.Reverse(four);
                                        Array.Reverse(five);
                                        Array.Reverse(six);
                                    }
                                    Int16 onevalue = BitConverter.ToInt16(one, 0);
                                    Int16 twovalue = BitConverter.ToInt16(two, 0);
                                    Int16 threevalue = BitConverter.ToInt16(three, 0);
                                    Int16 fourvalue = BitConverter.ToInt16(four, 0);
                                    Int16 fivevalue = BitConverter.ToInt16(five, 0);
                                    Int16 sixvalue = BitConverter.ToInt16(six, 0);

                                    String signal = "功率状态:" + onevalue + "-" + twovalue + "-" + threevalue +
                                        "-" + fourvalue + "-" + fivevalue + "-" + sixvalue;

                                    form1.AppendString(DateTime.Now.ToString() + " " + signal);
                                }
                                else if (str.StartsWith("2444575858"))
                                {//$DWXX
                                    byte[] useraddr = new byte[] { 0, readBuffer[7], readBuffer[8], readBuffer[9] };
                                    byte[] addr = new byte[] { 0, readBuffer[11], readBuffer[12], readBuffer[13] };
                                    byte[] h = new byte[] { (byte)0, readBuffer[14] };
                                    byte[] m = new byte[] { (byte)0, readBuffer[15] };
                                    byte[] s = new byte[] { (byte)0, readBuffer[16] };
                                    byte[] ss = new byte[] { (byte)0, readBuffer[17] };

                                    byte[] L = new byte[] { (byte)0, readBuffer[18] };
                                    byte[] LL = new byte[] { (byte)0, readBuffer[19] };
                                    byte[] LLL = new byte[] { (byte)0, readBuffer[20] };
                                    byte[] LLLL = new byte[] { (byte)0, readBuffer[21] };

                                    byte[] B = new byte[] { (byte)0, readBuffer[22] };
                                    byte[] BB = new byte[] { (byte)0, readBuffer[23] };
                                    byte[] BBB = new byte[] { (byte)0, readBuffer[24] };
                                    byte[] BBBB = new byte[] { (byte)0, readBuffer[25] };

                                    byte[] MS = new byte[] { (byte)0, readBuffer[26] };
                                    byte[] M = new byte[] { (byte)0, readBuffer[27] };

                                    byte[] HS = new byte[] { (byte)0, readBuffer[28] };
                                    byte[] H = new byte[] { (byte)0, readBuffer[29] };
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(useraddr);
                                        Array.Reverse(addr);
                                        Array.Reverse(h);
                                        Array.Reverse(m);
                                        Array.Reverse(s);
                                        Array.Reverse(ss);
                                        Array.Reverse(L);
                                        Array.Reverse(LL);
                                        Array.Reverse(LLL);
                                        Array.Reverse(LLLL);
                                        Array.Reverse(B);
                                        Array.Reverse(BB);
                                        Array.Reverse(BBB);
                                        Array.Reverse(BBBB);
                                        Array.Reverse(MS);
                                        Array.Reverse(M);
                                        Array.Reverse(HS);
                                        Array.Reverse(H);
                                    }
                                    Int32 useraddress = BitConverter.ToInt32(useraddr, 0);
                                    Int32 address = BitConverter.ToInt32(addr, 0);
                                    Int16 hvalue = BitConverter.ToInt16(h, 0);
                                    Int16 mvalue = BitConverter.ToInt16(m, 0);
                                    Int16 svalue = BitConverter.ToInt16(s, 0);
                                    Int16 ssvalue = BitConverter.ToInt16(ss, 0);
                                    Int16 lvalue = BitConverter.ToInt16(L, 0);
                                    Int16 llvalue = BitConverter.ToInt16(LL, 0);
                                    Int16 lllvalue = BitConverter.ToInt16(LLL, 0);
                                    Int16 llllvalue = BitConverter.ToInt16(LLLL, 0);
                                    Int16 bvalue = BitConverter.ToInt16(B, 0);
                                    Int16 bbvalue = BitConverter.ToInt16(BB, 0);
                                    Int16 bbbvalue = BitConverter.ToInt16(BBB, 0);
                                    Int16 bbbbvalue = BitConverter.ToInt16(BBBB, 0);
                                    Int16 MSvalue = BitConverter.ToInt16(MS, 0);
                                    Int16 Mvalue = BitConverter.ToInt16(M, 0);
                                    Int16 hsvalue = BitConverter.ToInt16(HS, 0);
                                    Int16 Hvalue = BitConverter.ToInt16(H, 0);
                                    int GAODU = Mvalue;
                                    int gaoduyichang = Hvalue;

                                    if (hsvalue == 1)
                                    {
                                        gaoduyichang = gaoduyichang * (-1);
                                    }
                                    if (MSvalue == 1)
                                    {
                                        GAODU = GAODU * (-1);
                                    }

                                    String DingweiInfo = " " + hvalue + "时" + mvalue + "分" + svalue + "." + ssvalue + "秒" + " 用户地址 " + useraddress + " 查询地址 " + address +
                                                        " 经度 " + lvalue + "度" + llvalue + "分" + lllvalue + "." + llllvalue + "秒" +
                                                        " 纬度 " + bvalue + "度" + bbvalue + "分" + bbbvalue + "." + bbbbvalue + "秒" +
                                                        " 高度" + GAODU + "米" + " 高度异常" + gaoduyichang + "米";

                                    form1.AppendString(DateTime.Now + DingweiInfo);
                                }
                                else if (str.StartsWith("24464B5858"))
                                {//$FKXX                                
                                    byte[] value = new byte[2] { 0x0, readBuffer[10] };
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(value);
                                    }
                                    Int16 ret = BitConverter.ToInt16(value, 0);
                                    if (ret == 0)
                                    {
                                        byte[] byteArray = new byte[4] { readBuffer[11], readBuffer[12], readBuffer[13], readBuffer[14] };
                                        string data = byteToHexStr(byteArray, 4);
                                        if (data == "44575351")
                                        {
                                            form1.AppendString(DateTime.Now + " 反馈信息：定位申请发送成功");
                                        }
                                        else if (data == "54585351")
                                        {
                                            form1.AppendString(DateTime.Now + " 反馈信息：通信申请发送成功");
                                        }
                                        else
                                        {
                                            form1.AppendString(DateTime.Now + " 反馈信息：发送成功");
                                        }
                                    }
                                    else if (ret == 1)
                                    {
                                        byte[] byteArray = new byte[4] { readBuffer[11], readBuffer[12], readBuffer[13], readBuffer[14] };
                                        string data = byteToHexStr(byteArray, 4);
                                        if (data == "44575351")
                                        {
                                            form1.AppendString(DateTime.Now + " 反馈信息：定位申请发送失败");
                                        }
                                        else if (data == "54585351")
                                        {
                                            form1.AppendString(DateTime.Now + "  反馈信息：通信申请发送失败");
                                        }

                                    }
                                    else if (ret == 2)
                                    {
                                        form1.AppendString(DateTime.Now + " 反馈信息：信号未锁定");
                                    }
                                    else if (ret == 3)
                                    {
                                        form1.AppendString(DateTime.Now + " 反馈信息：电量不足");
                                    }
                                    else if (ret == 4)
                                    {//超频
                                        //
                                        byte[] waittime = new byte[4] { readBuffer[11], readBuffer[12], readBuffer[13], readBuffer[14] };
                                        Int32 time = BitConverter.ToInt32(waittime, 0);
                                        form1.AppendString(DateTime.Now + " 反馈信息：发射频度未到,再等待" + time + "秒！");

                                    }
                                    else if (ret == 5)
                                    {
                                        form1.AppendString(DateTime.Now + " 反馈信息：加解密错误");
                                    }
                                    else if (ret == 6)
                                    {
                                        form1.AppendString(DateTime.Now + " 反馈信息：CRC错误");
                                    }
                                }
                                else if (str.StartsWith("2454585858"))
                                {
                                    //通信信息TXXX
                                    byte xinxileibie = readBuffer[10];
                                    byte[] useraddr = new byte[] { 0, readBuffer[7], readBuffer[8], readBuffer[9] };
                                    byte[] remoteAddr = new byte[] { 0x0, readBuffer[11], readBuffer[12], readBuffer[13] };
                                    byte[] sendtimeh = new byte[] { 0x0, readBuffer[14] };
                                    byte[] sendtimem = new byte[] { 0x0, readBuffer[15] };
                                    byte[] contentBitlen = new byte[] { readBuffer[16], readBuffer[17] };
                                    byte fangshi = (byte)(xinxileibie & 0x60);
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(useraddr);
                                        Array.Reverse(contentBitlen);
                                        Array.Reverse(remoteAddr);
                                        Array.Reverse(sendtimeh);
                                        Array.Reverse(sendtimem);
                                    }

                                    Int16 contentlenvalue = BitConverter.ToInt16(contentBitlen, 0);
                                    Int16 sendtimehvalue = BitConverter.ToInt16(sendtimeh, 0);
                                    Int16 sendtimemnvalue = BitConverter.ToInt16(sendtimem, 0);
                                    Int32 receiveraddr = BitConverter.ToInt32(useraddr, 0);
                                    Int32 remoteAddrvalue = BitConverter.ToInt32(remoteAddr, 0);
                                    int contentlen = contentlenvalue / 8;//
                                    byte[] content = new byte[contentlen]; //
                                    for (int i = 0; i < contentlen; i++)
                                    {
                                        content[i] = readBuffer[18 + i];
                                    }
                                    String duanxin = "";  //
                                    String baowenfanshi = "";
                                    if (fangshi == 0x60)  //
                                    {
                                        byte[] newconent = new byte[content.Length - 1];
                                        if (content[0] == 0xA4)
                                        {
                                            for (int i = 0; i < contentlen - 1; i++)
                                            {
                                                newconent[i] = content[1 + i];
                                            }
                                            string xinxi = System.Text.Encoding.Default.GetString(newconent, 0, newconent.Length);
                                            duanxin = xinxi;
                                            baowenfanshi = "混发";
                                        }
                                        else
                                        {
                                            String hex = byteToHexStr(content, content.Length);
                                            baowenfanshi = "代码";
                                            duanxin = hex;
                                        }
                                    }
                                    else if (fangshi == 0x40)
                                    {
                                        string xinxi = System.Text.Encoding.Default.GetString(content, 0, content.Length);
                                        baowenfanshi = "汉字";
                                        duanxin = xinxi;
                                    }
                                    //提取短信信息
                                    form1.AppendString(DateTime.Now + " " + receiveraddr + " 收到" + baowenfanshi + "报文: 来自" + remoteAddrvalue + " 时间：" + sendtimehvalue + "时" + sendtimemnvalue + "分 " + "内容：" + duanxin);
                                    //byte[] bdSendDate;
                                    ////bdSendDate = System.Text.Encoding.Default.GetBytes(duanxin);
                                    //bdSendDate = Encoding.ASCII.GetBytes(duanxin);
                                    ////开始处理接收到的信息
                                    //for (int i = 0; i < bdSendDate.Length; i++)
                                    //{
                                    //    form1.AppendString(bdSendDate[i] + "");
                                    //}
                                    form1.SegmentMessageForBD(duanxin );
                                    form1.AppendString("接收到卫星通讯消息" );
                                }
                                else
                                {
                                    //from1.AppendString(DateTime.Now + " ：" + str);
                                }

                                if (tmp == (byte)0x24)
                                {
                                    readBuffer[0] = tmp;
                                    bytecount = 1;
                                }
                                else
                                {
                                    bytecount = 0;
                                }
                            }
                            else if (tmp == (byte)0x0A && readBuffer[bytecount - 1] == (byte)0x0D)//判断BD2/GPS数
                            {//RN
                                //string gpsdata = System.Text.Encoding.Default.GetString(readBuffer, 0, readBuffer.Length).Trim(); //根据ASCII获取短报文内容                               
                                //if (BD2GPSCK.Checked)//是否显示二代数据
                                {
                                    //AppendString(gpsdata);
                                }
                                readBuffer = new byte[300];
                                bytecount = 0;
                            }
                            else
                            {
                                try
                                {
                                    readBuffer[bytecount++] = tmp;
                                }
                                catch
                                {
                                    bytecount = 0;
                                }
                            }
                        }
                        else
                        {
                            //计数还是为零的时候判断是是否检测到‘$’
                            if (tmp == (byte)0x24)
                            {
                                readBuffer[bytecount++] = tmp;
                            }
                        }
                    }
                    catch (TimeoutException) { }
                }
                else
                { //如果串口没打开
                    //TimeSpan waitTime = new TimeSpan(0, 0, 0, 0, 50);
                    int waitTime = 100;
                    Thread.Sleep(waitTime);
                }
            }
        }
        //字节转换Hexstriing
        public  static string byteToHexStr(byte[] bytes, int len)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < len; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        //获取 数据长度
        private int Datalen(byte[] buffer)
        {
            byte[] len = new byte[] { (byte)0, (byte)0, buffer[5], buffer[6] };
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(len);
            }
            int ret = BitConverter.ToInt32(len, 0);
            return ret;
        }
        //IC检测
        public void ICDetection()
        {
            if (!sp.IsOpen)
            {
                form1.AppendString("北斗通信串口未打开");
                return;
            }
            byte[] send = new byte[] { 0x24, 0x49, 0x43, 0x4A, 0x43, 0x00, 0x0C, 0x0, 0x0, 0x0, 0x1, 0x2A };
            try
            {
                sp.Write(send, 0, send.Length);
            }
            catch { }
            form1.AppendString(DateTime.Now + " IC检测");
        }
        //功率检测
        public void PowerDetection()
        {
            if (!sp.IsOpen)
            {
                form1.AppendString("北斗通信串口未打开");
                return;
            }
            byte[] send = new byte[] { 0x24, 0x47, 0x4C, 0x4A, 0x43, 0x00, 0x0C, 0x0, 0x0, 0x0, 0x1, 0x2b };
            sp.Write(send, 0, send.Length);
            form1.AppendString(DateTime.Now + " 功率检测");
        }
        //单次定位
        public void SingleLocation()
        {
            if (!sp.IsOpen)
            {
                form1.AppendString("串口未打开");
                return;
            }
            byte[] cmddw = new byte[] { 0x24, 0x44, 0x57, 0x53, 0x51, 0x0, 0x16, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x27 };
            sp.Write(cmddw, 0, cmddw.Length);
            form1.AppendString(DateTime.Now + " 单次定位");
        }
        //单次通信——发送报文(sting )
        public void SingleCommunication_byte(string ID,byte[] bytes)
        {
            string message = byteToHexStr(bytes, bytes.Length);

            if (!sp.IsOpen)
            {
                form1.AppendString("北斗通信串口未打开");
                return;
            }
            Int32 addr = 0;
            if (ID != "" && ID != null)
            {
                addr = System.Int32.Parse(ID);
            }
            else
            {
                form1.AppendString("未输入对方卡号");
                return;
            }
            byte[] addrbytes = System.BitConverter.GetBytes(addr);
            byte l = addrbytes[0];
            byte m = addrbytes[1];
            byte h = addrbytes[2];
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(addrbytes);
            }

            String sms = message;
            byte[] smsbytes;
            Int32 contentLen = 0;
            int fangshi = 1;//使用代码发送
            byte[] xinxileibie = new byte[1];
            if (fangshi == 2)
            {
                xinxileibie[0] = 0x44;//汉字
                smsbytes = System.Text.Encoding.Default.GetBytes(sms);
                contentLen = smsbytes.Length;
            }
            else if (fangshi == 0)
            {
                xinxileibie[0] = 0x46; //混发
                smsbytes = System.Text.Encoding.Default.GetBytes(sms);
                contentLen = smsbytes.Length;
            }
            else
            { //选择代码发送
                xinxileibie[0] = 0x46;//代码
                //以下处理仅是测试软件为了方便测试看到效果做的处理，实际协议应用不需要怎么处理
                byte[] data = System.Text.Encoding.Default.GetBytes(sms);
                if (data.Length > 0)
                {
                    if (data.Length % 2 == 0)
                    {
                        smsbytes = new byte[data.Length / 2];
                        for (int i = 0, j = 0; i < data.Length; i += 2, j++)
                        {
                            byte a = (byte)((data[i] - 0x30) & 0x0f);//取偶数 0011 0000   00001111
                            byte b = (byte)((data[i + 1] - 0x30) & 0x0f);//取奇数
                            smsbytes[j] = (byte)(a << 4 | b);
                        }
                        contentLen = smsbytes.Length;
                    }
                    else
                    {
                        smsbytes = new byte[data.Length / 2 + 1];
                        for (int i = 0, j = 0; i < data.Length - 1; i += 2, j++)
                        {
                            byte a = (byte)((data[i] - 0x30) & 0x0f);
                            byte b = (byte)((data[i + 1] - 0x30) & 0x0f);
                            smsbytes[j] = (byte)(a << 4 | b);
                        }
                        form1.AppendString("代码方式奇数位末尾补F");
                        smsbytes[data.Length / 2] = (byte)(((data[data.Length - 1] - 0x30) & 0x0f) << 4 | 0x0f);
                        contentLen = smsbytes.Length;
                    }
                }
                else
                {
                    smsbytes = new byte[0];
                }
            }
            Int32 contentLenbit = contentLen * 8;//电文内容长度(比特数)
            if (fangshi == 0)
            { //混发
                contentLen += 1;
                contentLenbit += 8; //多了一个0xA4  比特数加8
            }
            if (contentLenbit > 1680)
            {
                form1.AppendString("输入内容长度为" + contentLenbit + "bit大于允许最大长度1680bit");
                return;
            }
            Int32 len = contentLen + 18;
            byte[] cmdtxsq = new byte[len];
            cmdtxsq[0] = 0x24;
            cmdtxsq[1] = 0x54;
            cmdtxsq[2] = 0x58;
            cmdtxsq[3] = 0x53;
            cmdtxsq[4] = 0x51;
            cmdtxsq[5] = (byte)(len >> 8 & 0x000000FF);
            cmdtxsq[6] = (byte)(len & 0x000000FF);
            cmdtxsq[7] = 0x0;
            cmdtxsq[8] = 0x0;
            cmdtxsq[9] = 0x0;
            cmdtxsq[10] = xinxileibie[0];
            cmdtxsq[11] = addrbytes[1];
            cmdtxsq[12] = addrbytes[2];
            cmdtxsq[13] = addrbytes[3];
            cmdtxsq[14] = (byte)(contentLenbit >> 8 & 0x000000ff);
            cmdtxsq[15] = (byte)(contentLenbit & 0x000000ff);
            cmdtxsq[16] = 0x0;

            if (fangshi == 0)
            {
                cmdtxsq[17] = 0xA4;
                for (int i = 0; i < smsbytes.Length; i++)
                {
                    cmdtxsq[18 + i] = smsbytes[i];
                }
            }

            else
            {
                for (int i = 0; i < smsbytes.Length; i++)
                {
                    cmdtxsq[17 + i] = smsbytes[i];
                }
            }
            cmdtxsq[len - 1] = bd_get_checksum(cmdtxsq, len - 1);

            sp.Write(cmdtxsq, 0, cmdtxsq.Length);

            form1.AppendString(DateTime.Now + " 通信申请 发往:" + ID + " 内容:" + message);
        }
        //单次通信——发送报文(byte )
        //public void SingleCommunication_byte(string ID, byte[] sendDate)
        //{
        //    if (!sp.IsOpen)
        //    {
        //        form1.AppendString("北斗通信串口未打开");
        //        return;
        //    }
        //    Int32 addr = 0;
        //    if (ID != "" && ID != null)
        //    {
        //        addr = System.Int32.Parse(ID);
        //    }
        //    else
        //    {
        //        form1.AppendString("未输入对方卡号");
        //        return;
        //    }
        //    byte[] addrbytes = System.BitConverter.GetBytes(addr);
        //    byte l = addrbytes[0];
        //    byte m = addrbytes[1];
        //    byte h = addrbytes[2];
        //    if (BitConverter.IsLittleEndian)
        //    {
        //        Array.Reverse(addrbytes);
        //    }

        //    //String sms = message;
        //    byte[] smsbytes = new byte[sendDate.Length];
        //    sendDate.CopyTo(smsbytes, 0);
        //    Int32 contentLen = 0;
        //    int fangshi = 1;//使用代码发送
        //    byte[] xinxileibie = new byte[1];
        //    //smsbytes = System.Text.Encoding.Default.GetBytes(sms);
        //    contentLen = smsbytes.Length;
        //    if (fangshi == 2)
        //    {
        //        xinxileibie[0] = 0x44;//汉字
                
        //    }
        //    else if (fangshi == 0)
        //    {
        //        xinxileibie[0] = 0x46; //混发
        //    }
        //    else
        //    { //选择代码发送
        //        xinxileibie[0] = 0x46;//代码
        //        //以下处理仅是测试软件为了方便测试看到效果做的处理，实际协议应用不需要怎么处理
        //        byte[] data = new byte[sendDate.Length];
        //        sendDate.CopyTo(data, 0);
        //        if (data.Length > 0)
        //        {
        //            if (data.Length % 2 == 0)
        //            {
        //                smsbytes = new byte[data.Length / 2];
        //                for (int i = 0, j = 0; i < data.Length; i += 2, j++)
        //                {
        //                    byte a = (byte)((data[i] - 0x30) & 0x0f);//取偶数 0011 0000   00001111
        //                    byte b = (byte)((data[i + 1] - 0x30) & 0x0f);//取奇数
        //                    smsbytes[j] = (byte)(a << 4 | b);
        //                }
        //                contentLen = smsbytes.Length;
        //            }
        //            else
        //            {
        //                smsbytes = new byte[data.Length / 2 + 1];
        //                for (int i = 0, j = 0; i < data.Length - 1; i += 2, j++)
        //                {
        //                    byte a = (byte)((data[i] - 0x30) & 0x0f);
        //                    byte b = (byte)((data[i + 1] - 0x30) & 0x0f);
        //                    smsbytes[j] = (byte)(a << 4 | b);
        //                }
        //                form1.AppendString("代码方式奇数位末尾补F");
        //                smsbytes[data.Length / 2] = (byte)(((data[data.Length - 1] - 0x30) & 0x0f) << 4 | 0x0f);
        //                contentLen = smsbytes.Length;
        //            }
        //        }
        //        else
        //        {
        //            smsbytes = new byte[0];
        //        }
        //    }
        //    Int32 contentLenbit = contentLen * 8;//电文内容长度(比特数)
        //    if (fangshi == 0)
        //    { //混发
        //        contentLen += 1;
        //        contentLenbit += 8; //多了一个0xA4  比特数加8
        //    }
        //    if (contentLenbit > 1680)
        //    {
        //        form1.AppendString("输入内容长度为" + contentLenbit + "bit大于允许最大长度1680bit");
        //        return;
        //    }
        //    Int32 len = contentLen + 18;
        //    byte[] cmdtxsq = new byte[len];
        //    cmdtxsq[0] = 0x24;
        //    cmdtxsq[1] = 0x54;
        //    cmdtxsq[2] = 0x58;
        //    cmdtxsq[3] = 0x53;
        //    cmdtxsq[4] = 0x51;
        //    cmdtxsq[5] = (byte)(len >> 8 & 0x000000FF);
        //    cmdtxsq[6] = (byte)(len & 0x000000FF);
        //    cmdtxsq[7] = 0x0;
        //    cmdtxsq[8] = 0x0;
        //    cmdtxsq[9] = 0x0;
        //    cmdtxsq[10] = xinxileibie[0];
        //    cmdtxsq[11] = addrbytes[1];
        //    cmdtxsq[12] = addrbytes[2];
        //    cmdtxsq[13] = addrbytes[3];
        //    cmdtxsq[14] = (byte)(contentLenbit >> 8 & 0x000000ff);
        //    cmdtxsq[15] = (byte)(contentLenbit & 0x000000ff);
        //    cmdtxsq[16] = 0x0;

        //    if (fangshi == 0)
        //    {
        //        cmdtxsq[17] = 0xA4;
        //        for (int i = 0; i < smsbytes.Length; i++)
        //        {
        //            cmdtxsq[18 + i] = smsbytes[i];
        //        }
        //    }

        //    else
        //    {
        //        for (int i = 0; i < smsbytes.Length; i++)
        //        {
        //            cmdtxsq[17 + i] = smsbytes[i];
        //        }
        //    }
        //    cmdtxsq[len - 1] = bd_get_checksum(cmdtxsq, len - 1);

        //    sp.Write(cmdtxsq, 0, cmdtxsq.Length);

        //    form1.AppendString(DateTime.Now + " 通信申请 发往:" + ID);
        //}
       //求异或
        private byte bd_get_checksum(byte[] bytes, int slen)
        {
            byte ch = 0;
            int i = 0;
            for (i = 0; i < slen; i++)
            {
                byte h;
                h = bytes[i];
                ch ^= h;
            }
            return ch;
        }
    }
}
